package com.example.extension.framework.config;

import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.stereotype.Component;

import com.example.extension.framework.ExtensionPoint;
import com.example.extension.framework.ScenarioCapable;

//@RefreshScope
@Component
@ConfigurationProperties(prefix = "extension-config")
public class ExtensionConfigBean {

    // K=租户编号 V= Map<String, String>(K=扩展点编号 V=扩展实现编号)
    private Map<String, Map<String, String>> tenantMap;

    public Map<String, Map<String, String>> getTenantMap() {
        return tenantMap;
    }

    public void setTenantMap(Map<String, Map<String, String>> tenantMap) {
        this.tenantMap = tenantMap;
    }

    public String getScenarioCode(String tenantCode, Class<?> superType) {
        // 返回值赋初始值
        String scenario = ScenarioCapable.SCENARIO_CODE_DEFAULT;
        if (getTenantMap() == null || !tenantMap.containsKey(tenantCode)) {
            return scenario;
        }
        
        Map<String, String> extensionConfigMap = tenantMap.get(tenantCode);
        // 根据接口获取扩展点Code
        ExtensionPoint superAnno = AnnotationUtils.findAnnotation(superType, ExtensionPoint.class);
        String extPointCode =
            superAnno == null || StringUtils.isBlank(superAnno.value()) ? superType.getName() : superAnno.value();
        if (extensionConfigMap.containsKey(extPointCode)) {
            scenario = extensionConfigMap.get(extPointCode);
        }
        return scenario;
    }

}
